package top.huxy.boot.util.schedule;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.huxy.boot.config.Constant;
import top.huxy.boot.model.entity.ScheduleJob;
import top.huxy.boot.util.StringUtils;

@Slf4j
@Component
public class ScheduleUtils {

    @Autowired
    Scheduler scheduler;

    public void addSchedule(ScheduleJob scheduleJob) {

        //创建任务执行逻辑
        JobDetail jobDetail = JobBuilder.newJob(ScheduleRunnable.class)
                .withIdentity(scheduleJob.getJobId().toString())
                .build();

        //创建执行方式
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(scheduleJob.getJobId().toString())
                .startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule(scheduleJob.getCron())
                        .withMisfireHandlingInstructionDoNothing()).build();
        //下面代码好像没用
//        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCron()).withMisfireHandlingInstructionDoNothing();
//        Trigger trigger = TriggerBuilder.newTrigger()
//                .withSchedule(cronScheduleBuilder)
//                .build();

        //设置变量，好在任务执行时能获取到一些参数
        jobDetail.getJobDataMap().put(Constant.TIMER_TASK_NAME, scheduleJob);
        try {
            //执行任务
            scheduler.scheduleJob(jobDetail, trigger);
            log.info("添加任务成功，任务id{}", scheduleJob.getJobId());
        } catch (SchedulerException e) {
            log.error("创建任务失败", e);
            throw new RuntimeException("创建任务失败", e);
        }
    }

    public void stopSchedule(Integer scheduleId) {
        try {
            scheduler.deleteJob(new JobKey(scheduleId.toString()));
        } catch (SchedulerException e) {
            log.error("停止任务失败",e);
            throw new RuntimeException(e);
        }
    }

    public void runOnce(ScheduleJob scheduleJob){

        //创建任务执行逻辑
        JobDetail jobDetail = JobBuilder.newJob(ScheduleRunnable.class)
                .withIdentity(StringUtils.unique())
                .build();

        //创建执行方式，只执行一次

        SimpleTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(StringUtils.unique())
                .startNow()
                .withSchedule(SimpleScheduleBuilder
                        .simpleSchedule()
                        .withRepeatCount(0)).build();

        //设置变量，好在任务执行时能获取到一些参数
        jobDetail.getJobDataMap().put(Constant.TIMER_TASK_NAME, scheduleJob);
        try {
            //执行任务
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            throw new RuntimeException("创建任务失败", e);
        }
    }
}
